package com.web44.ssm.web;

import com.web44.ssm.utils.ResponseVo;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @Title: ImageController
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2024/1/17 9:03
 */
@RestController
@RequestMapping("upload")
public class ImageController {

    /**
     * 文件名字是原始的名字 可以覆盖
     * 上传到当前项目的目录下
     * @param face 上传的源文件
     * @return
     */
    @PostMapping("face")
    public ResponseVo  uploadWeb(@RequestParam("face") MultipartFile face, HttpServletRequest request) throws IOException {

        // 获取原来的文件名称
        String originalFilename = face.getOriginalFilename();
        // 获取文件的类型
        String extension = FilenameUtils.getExtension(originalFilename);

        // 获取项目根路径
        String projectPath = request.getServletContext().getRealPath("/images");
        // 上传的资源路径  xxxx/xxx/xxx
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String format = now.format(formatter);
        String fileName = UUID.randomUUID().toString().replaceAll("-","")+"."+extension;


        File rootFile = new File(projectPath+"/"+format);
        if(!rootFile.exists()) {
            rootFile.mkdirs();
        }
        rootFile = new File(rootFile,fileName);

        face.transferTo(rootFile);

         return ResponseVo.ok("上传文件成功！","/images/"+format+"/"+fileName);
    }
}
